#include "MessageServer.h"
#include "Log.h"
//=================MessageServer=================//
MessageServer* MessageServer::Instance = NULL;

MessageServer::MessageServer(){}
MessageServer::~MessageServer(){}
void MessageServer::Alloc(){
	if (!Instance)
		Instance = new MessageServer;
}
void MessageServer::Malloc(){
	SAFE_DEL(Instance);
}
void MessageServer::Clear(){
	std::map<FWuint, std::vector<_Subscriber>>::iterator temp = m_lstSubscribers.begin();
	for (; temp != m_lstSubscribers.end(); temp++){
		temp->second.clear();
	}
	m_lstSubscribers.clear();
}
void MessageServer::ExecuteTag(_Publisher publisher){
	std::map<FWuint, std::vector<_Subscriber>>::iterator temp = m_lstSubscribers.find(publisher.Tag);
	if (temp == m_lstSubscribers.end())
		return;
	FWuint count = temp->second.size();
	for (FWuint i = 0; i < count; i++){
		temp->second.at(i).CallBack(publisher.Sender, publisher.Extra);
	}
}

void MessageServer::Register(FWobject reciever, FWuint tag, void(*callBack)(const FWobject, FWobject)){
	_Subscriber subscrib;
	subscrib.CallBack = callBack;
	subscrib.Reciever = reciever;
	std::map<FWuint, std::vector<_Subscriber>>::iterator temp = m_lstSubscribers.find(tag);
	if (temp == m_lstSubscribers.end()){
		std::vector<_Subscriber> data;
		data.resize(0);
		data.push_back(subscrib);
		m_lstSubscribers[tag] = data;
	}
	else{
		temp->second.push_back(subscrib);
	}
}

void MessageServer::Send(const FWobject sender, FWuint tag, FWobject extra){
	_Publisher publisher = _Publisher();
	publisher.Tag = tag;
	publisher.Sender = sender;
	publisher.Extra = extra;

	ExecuteTag(publisher);
}